from sqlalchemy import Column, ForeignKey, Integer, Table
from sqlalchemy.orm import Mapped, backref, mapped_column, relationship

from dc_shop.database.models.base import TimedBaseModel

orders_users = Table(
    "orders_users",
    TimedBaseModel.metadata,
    Column("order_id", Integer, ForeignKey("order.id")),
    Column("user_id", Integer, ForeignKey("user.id")),
)

products_feelings = Table(
    "product_feelings",
    TimedBaseModel.metadata,
    Column("product_id", Integer, ForeignKey("product.id")),
    Column("feeling_id", Integer, ForeignKey("feeling.id")),
)

products_genetics = Table(
    "products_genetics",
    TimedBaseModel.metadata,
    Column("product_id", Integer, ForeignKey("product.id")),
    Column("genetics_id", Integer, ForeignKey("genetics.id")),
)

promocodes_users = Table(
    "promocodes_users",
    TimedBaseModel.metadata,
    Column("promocode_id", Integer, ForeignKey("promocode.id")),
    Column("user_id", Integer, ForeignKey("user.id")),
)


class CartProduct(TimedBaseModel):
    __tablename__ = "cart_product"
    __mapper_args__ = {"eager_defaults": True}

    id: Mapped[int] = mapped_column(primary_key=True)
    product = relationship("Product", backref=backref("cart_products", cascade="all,delete"))
    product_id: Mapped[int] = mapped_column(ForeignKey("product.id"))
    cart = relationship("Cart", back_populates="products")
    cart_id: Mapped[int] = mapped_column(ForeignKey("cart.id"), nullable=True)
    quantity: Mapped[int]

    def __repr__(self):
        return f"<Товар №{self.product_id}, количество: {self.quantity}"

    def __str__(self):
        return self.__repr__()


class OrderLine(TimedBaseModel):
    __tablename__ = "order_line"
    __mapper_args__ = {"eager_defaults": True}

    id: Mapped[int] = mapped_column(primary_key=True)
    order_id: Mapped[int] = mapped_column(ForeignKey("order.id", ondelete="CASCADE"))
    product = relationship("Product", backref=backref("order_lines", cascade="all,delete"))
    product_id: Mapped[int] = mapped_column(ForeignKey("product.id"))
    quantity: Mapped[int]

    def __repr__(self):
        return f"<Заказ №{self.id}, товар №{self.product_id}>"

    def __str__(self):
        return self.__repr__()
